<template>
  <div class="index">
    <!-- 顶部 -->
    <div class="top"><Admin></Admin></div>
    <!-- bottom -->
    <div class="bottom">
      <div class="left"><SideNav></SideNav></div>
      <div class="right">
        <div class="content">
          <el-scrollbar style="height: 100%;">
            <!-- 当前位置 -->
            <div class="current_position">
              <p class="breadcrumb">当前位置 :</p>
              <el-breadcrumb separator="/">
                <el-breadcrumb-item class="up">设备管理</el-breadcrumb-item>
                <el-breadcrumb-item>设备列表</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <!-- 会员列表 -->
            <div class="userlist">
              <div class="status_box">
                <div class="input" @keyup.enter="findUser()">
                  <el-input v-model="input" placeholder="设备名/代理人/手机号" clearable></el-input>
                </div>
                <div class="search"><el-button @click="findUser()">搜索</el-button></div>
                <div class="add"><el-button @click="dialogVisible = true">新增</el-button></div>
              </div>
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="使用中" name="first"></el-tab-pane>
                <el-tab-pane label="待机中" name="second"></el-tab-pane>
                <el-tab-pane label="已停用" name="third"></el-tab-pane>
              </el-tabs>
              <div class="table">
                <el-table ref="multipleTable" :data="tableData" border tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" fixed="left" width="50"></el-table-column>
                  <el-table-column prop="id" label="设备ID" width="100"></el-table-column>
                  <el-table-column prop="name" label="设备名"></el-table-column>
                  <el-table-column prop="address" label="设备地址"></el-table-column>
                  <el-table-column prop="sn" label="设备sn"></el-table-column>
                  <el-table-column prop="cameraSn" label="摄像头sn"></el-table-column>
                  <el-table-column prop="id" label="代理人">
                    <template slot-scope="scope">
                      <span>{{scope.row.wechatNickname}}/{{scope.row.mobile}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right"  width="230">
                    <template slot-scope="scope">
                      <el-button @click="goToUserListDetails(scope.row)" type="text" size="small">编辑</el-button>
                      <span class="line">|</span>
                      <el-button @click="dialogVisible2 = true,Details(scope.row)" type="text" size="small">设置价格</el-button>
                      <span class="line">|</span>
                      <el-button @click="dialogVisible3 = true,Details3(scope.row)" type="text" size="small">绑定会员卡</el-button>
                      <span class="line">|</span>
                      <el-button @click="del(scope.row)" type="text" size="small">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[50,100,150,200,250]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">
                </el-pagination>
              </div>
            </div>
          </el-scrollbar>
          <el-dialog title="新增设备" :visible.sync="dialogVisible"  width="35%" :before-close="handleClose1">
            <el-form :model="equipmentForm" ref="equipmentForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="设备名" prop="name">
                <el-input v-model="equipmentForm.name" class="equipmentInput"></el-input>
              </el-form-item>
              <el-form-item label="绑定代理" prop="agencyId">
                <el-select v-model="equipmentForm.agencyId" @focus="getAgency()"  class="equipmentInput">
                  <el-option  v-for="item in options1"  :key="item.id"  :label="item.phoneNumber"  :value="item.id">{{item.wechatNickname}}/{{item.phoneNumber}}</el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="联系电话" prop="mobile">
                <el-input v-model="equipmentForm.mobile" class="equipmentInput"></el-input>
              </el-form-item>
              <el-form-item label="设备sn" prop="sn">
                <el-input v-model="equipmentForm.sn" class="equipmentInput"></el-input>
              </el-form-item>
              <el-form-item label="设备地址:">
                <el-input v-model="equipmentForm.address" clearable></el-input>
              </el-form-item>
              <el-form-item label="经纬度:">
                <div class="property">
                  <el-input class="lng" v-model="equipmentForm.lng" clearable></el-input>
                  <el-input class="lat" v-model="equipmentForm.lat" clearable></el-input>
                </div>
              </el-form-item>
              <el-form-item label="摄像头sn" prop="cameraSn">
                <el-input v-model="equipmentForm.cameraSn" class="equipmentInput"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitequipmentForm('equipmentForm')">确 定</el-button>
              <el-button @click="dialogVisible = false">取 消</el-button>
            </span>
          </el-dialog>
          <el-dialog title="设置价格" :visible.sync="dialogVisible2"  width="35%" :before-close="handleClose2">
            <el-form :model="priceForm" ref="priceForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="设备使用费：" prop="timePrice">
                <el-input v-model="priceForm.timePrice" class="priceInput" placeholder="保留至分"></el-input>
                <span>元/分钟</span>
              </el-form-item>
              <el-form-item label="清水：" prop="waterPrice">
                <el-input v-model="priceForm.waterPrice" class="priceInput" placeholder="保留至分"></el-input>
                <span>元/分钟</span>
              </el-form-item>
              <el-form-item label="泡沫：" prop="foamPrice">
                <el-input v-model="priceForm.foamPrice" class="priceInput" placeholder="保留至分"></el-input>
                <span>元/分钟</span>
              </el-form-item>
              <el-form-item label="吸尘：" prop="vacuumPrice">
                <el-input v-model="priceForm.vacuumPrice" class="priceInput" placeholder="保留至分"></el-input>
                <span>元/分钟</span>
              </el-form-item>
              <el-form-item label="洗手：" prop="washPrice">
                <el-input v-model="priceForm.washPrice" class="priceInput" placeholder="保留至分"></el-input>
                <span>元/分钟</span>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="dialogVisible2 = false,submitpriceForm()">确 定</el-button>
              <el-button @click="dialogVisible2 = false">取 消</el-button>
            </span>
          </el-dialog>
          <el-dialog title="绑定会员卡" :visible.sync="dialogVisible3"  width="25%" :before-close="handleClose3">
            <p class="bindname">设备名/ID:{{bindName}}</p>
            <el-checkbox-group v-model="bindForm">
              <el-checkbox v-for="(bind,index) in bindList" :label="bind.id" :key="index">
                {{bind.id}}/{{bind.name}}/
                <i v-if="bind.type==1">{{bind.userTime}}天</i>
                <i v-if="bind.type==2">{{bind.times}}次</i>
                /{{bind.sale}}元
              </el-checkbox>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="dialogVisible3 = false,submitbindForm()">确 定</el-button>
              <el-button @click="dialogVisible3 = false">取 消</el-button>
            </span>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  let moment = require("moment")
  import Admin from '@/components/Admin.vue'
  import SideNav from '@/components/SideNav.vue'

  export default {
    name: 'Equipment',
    components:{
      Admin,
      SideNav
    },
    data () {
      return {
        status:2,//设备状态
        activeName: 'first',
        page: 1,//页码
        pageSize: 50,//每页条数
        total: 0,/* 总的条数 */
        currentPage: 0,/* 前往第几页 */
        input: null,// 搜索输入框
        tableData: [], // 会员表格
        multipleSelection: [], // 选择后的列表
        dialogVisible: false,//新增设备弹窗
        equipmentForm:{//新增设备弹窗表单
          // equipmentId:'',//设备id
          name:'',//设备名称
          agencyId:'',//代理id
          address:'',//拿货地址
          lat:'',//纬度
          lng:'',//经度
          sn:'',//设备sn
          mobile:'',//设备手机号码
          cameraSn:'',//摄像头sn
        },
        equipmentRules:{//新增设备弹窗表单规则
          equipmentId:[
            { required: true, message: '不能为空', trigger: 'blur' },
          ],
          equipmentName:[
            { required: true, message: '不能为空', trigger: 'blur' },
          ],
          agencyId:[
            { required: true, message: '不能为空', trigger: 'blur' },
          ],
        },
        options1: [],//代理列表
        dialogVisible2: false,//设置价格弹窗
        priceForm:{
          status1:0,//0：为空新增  1：不为空更新
          id:'',
          timePrice:'',
          waterPrice:'',
          foamPrice:'',
          vacuumPrice:'',
          washPrice:'',
        },//新增价格弹窗表单
        priceRules:{//新增价格弹窗表单规则
          priceId:[
            { required: true, message: '不能为空', trigger: 'blur' },
          ]
        },
        dialogVisible3: false,//设绑定会员卡弹窗
        bindForm:[],//设备 已经 绑定会员卡表单
        bindList:[],//所有会员卡
        bindName:'',//设备名称
        bindId:null,//设备id
      }
    },
    mounted() {
      this.findUser();
    },
    methods: {
      // 切换tab
      handleClick(tab, event) {
        console.log(tab, event);
        if(tab.index ==0){
          this.status = 2;
          this.findUser();
        }else if(tab.index ==1){
          this.status = 1;
          this.findUser();
        }else{
          this.status = 3;
          this.findUser();
        }
      },
      // 时间格式过滤
      dateForma(row,column){
        var date = row[column.property];
        if(date == undefined){
          return ''
        }
        return moment(date).format("YYYY-MM-DD HH:mm:ss")
      },
      //所有设备
      findUser(){
        console.log("查找的内容："+this.input);
        this.$axios.post(this.baseURL+'device',{
          "key": this.input,
          "page": this.page,
          "pageSize":this.pageSize,
          "requestSource":"PC",
          "status":this.status,
        }).then((res)=>{
          console.log(res,"所有设备");
          if(res.data.code==1){
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      // 选择账号状态查找
      selectChanged(){
        console.log("选择账号状态："+this.value);
        this.input = "";//修改账号状态时清空输入框
        this.findUser();
      },
      // 表格的全选
      handleSelectionChange(val) {
        console.log(val);
        this.multipleSelection = val;
      },
      // 查看表格该列详情
      goToUserListDetails(row) {
        var data = row;
        this.$router.push({
          path: '/EquipmentDetails',
          query: {
            data: data,
          }
        })
      },
      // 选择的每页条数
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.findUser();// 获取产品列表
      },
      // 当前页面
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.page = val;
        this.findUser();
      },
      //关闭新增设备
      handleClose1(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //获取所有代理
      getAgency(){
        this.$axios.post(this.baseURL+'user',{
          "role":2,
          "requestSource":"PC"
        }).then((res)=>{
          console.log(res,"获取代理");
          if(res.data.code==1){
            this.options1 = res.data.data.records;
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //保存新增设备表单
      submitequipmentForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log('submit!');
            this.dialogVisible = false;//关闭弹窗
            console.log(this.equipmentForm);
            this.$axios.post(this.baseURL+'device/add',{
              "name":this.equipmentForm.name,//设备名称
              "agentId":this.equipmentForm.agencyId,//代理id
              "address":this.equipmentForm.address,//地址
              "lng":this.equipmentForm.lng,//纬度
              "lat":this.equipmentForm.lat,//经度
              "sn":this.equipmentForm.sn,//sn
              "mobile":this.equipmentForm.mobile,//手机
              "cameraSn":this.equipmentForm.cameraSn,//摄像头sn
              "status":1,//1：待机中
              "requestSource":"PC"
            }).then((res)=>{
              console.log(res,"新增设备");
              if(res.data.code==1){
                this.$message({
                  type: 'success',
                  message: '新增设备成功'
                });
                setTimeout(()=>{
                  this.findUser();
                  this.equipmentForm.name = "";
                  this.equipmentForm.agencyId = "";
                  this.equipmentForm.address = "";
                  this.equipmentForm.lng = "";
                  this.equipmentForm.lat = "";
                  this.equipmentForm.sn = "";
                  this.equipmentForm.mobile = "";
                  this.equipmentForm.cameraSn = "";
                },1000)
              }else{
                this.$message({
                  type: 'error',
                  message: res.data.msg
                });
              }
            }).catch((err)=>{
              console.log('request fail', err);
            })
          }else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //点击获取当前设备的设置价格
      Details(row){
        console.log(row)
        this.priceForm.status1 = 0
        this.priceForm.id= row.id
        this.priceForm.timePrice= null
        this.priceForm.waterPrice= null
        this.priceForm.foamPrice= null
        this.priceForm.vacuumPrice= null
        this.priceForm.washPrice= null
        this.$axios.post(this.baseURL+'price/info',{
          "deviceId": row.id,
          "requestSource":"PC",
        }).then((res)=>{
          console.log(res,"该设备价格列表");
          if(res.data.code==1 || res.data.data.timePrice!=null){
            this.priceForm.id= res.data.data.id
            this.priceForm.timePrice= res.data.data.timePrice
            this.priceForm.waterPrice= res.data.data.waterPrice
            this.priceForm.foamPrice= res.data.data.foamPrice
            this.priceForm.vacuumPrice= res.data.data.vacuumPrice
            this.priceForm.washPrice= res.data.data.washPrice
          }
          if(res.data.data.timePrice==null){
            this.priceForm.status1 = 0 // 新增
          }else{
            this.priceForm.status1 = 1// 更新
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //关闭设置价格
      handleClose2(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //提交设置价格方案
      submitpriceForm(){
        console.log("设备价格列表",this.priceForm)
        if(this.priceForm.status1 == 1){
          console.log("更新")
          this.submitpriceForm1()//更新
        }else{
          console.log("新增")
          this.submitpriceForm2() // 新增
        }
      },
      // 新增 价格
      submitpriceForm2(){
        this.dialogVisible = false;//关闭弹窗
        this.$axios.post(this.baseURL+'price/add',{
          "deviceId":this.priceForm.id,//设备id
          "timePrice":this.priceForm.timePrice,//设备使用费
          "waterPrice":this.priceForm.waterPrice,//清水费
          "foamPrice":this.priceForm.foamPrice,//泡沫费
          "vacuumPrice":this.priceForm.vacuumPrice,//吸尘费
          "washPrice":this.priceForm.washPrice,//洗手费
          // "status":2,//状态  默认停用状态
          "requestSource":"PC"
        }).then((res)=>{
          console.log(res,"新增设备");
          if(res.data.code==1){
            this.$message({
              type: 'success',
              message: '设置价格成功'
            });
            setTimeout(()=>{
              this.findUser();
            },1000)
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //更新
      submitpriceForm1(){
        this.dialogVisible = false;//关闭弹窗
        this.$axios.post(this.baseURL+'price/update',{
          "id":this.priceForm.id,//价格id
          "timePrice":this.priceForm.timePrice,//设备使用费
          "waterPrice":this.priceForm.waterPrice,//清水费
          "foamPrice":this.priceForm.foamPrice,//泡沫费
          "vacuumPrice":this.priceForm.vacuumPrice,//吸尘费
          "washPrice":this.priceForm.washPrice,//洗手费
          // "status":2,//状态  默认停用状态
          "requestSource":"PC"
        }).then((res)=>{
          console.log(res,"新增设备");
          if(res.data.code==1){
            this.$message({
              type: 'success',
              message: '设置价格成功'
            });
            setTimeout(()=>{
              this.findUser();
            },1000)
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //删除设备
      del(row){
        console.log(row)
        this.$confirm('确认删除该设备?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.post(this.baseURL+'device/del',{
            "ids": row.id,
            "requestSource":"PC",
          }).then((res)=>{
            console.log(res,"删除该设备");
            if(res.data.code==1){
              this.$message({
                type: 'success',
                message: '删除设备成功'
              });
              setTimeout(()=>{
                this.findUser();
              },1000)
            }else{
              this.$message({
                type: 'error',
                message: res.data.msg
              });
            }
          }).catch((err)=>{
            console.log('request fail', err);
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },
      //绑定会员卡
      Details3(row){
        console.log("设备id111",row.id)
        this.bindId = row.id
        if(row.name){
          this.bindName = row.name
        }else{
          this.bindName = row.id
        }
        this.getBindList(row.id)
      },
      //获取该设备绑定的卡列表
      getBindList(id){
        console.log("设备id222",id)
        this.bindForm = []
        this.$axios.post(this.baseURL+'deviceCard/deviceBindCardList',{
          "id": id,
          "requestSource":"PC",
        }).then((res)=>{
          if(res.data.code==1){
            this.bindList = res.data.data
            for (var i=0;i<res.data.data.length;i++){//遍历数组 将状态为1的会员卡勾选上
              if(res.data.data[i].status===1){
              	this.bindForm.unshift(res.data.data[i].id)
              }
            }
            console.log('已绑定id', this.bindForm);
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //关闭绑定会员卡
      handleClose3(done){
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //确定绑定会员卡
      submitbindForm(formName){
        console.log("设备id:",this.bindId)
        console.log(this.bindForm)
        this.$axios.post(this.baseURL+'deviceCard/bind',{
          "deviceId": this.bindId,
          "cardIds": this.bindForm,
          "requestSource":"PC",
        }).then((res)=>{
          if(res.data.code==1){
            this.$message({
              type: 'success',
              message: '绑定会员卡成功'
            });
            setTimeout(()=>{
              this.findUser();
            },1000)
            this.bindForm =[]
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  @import '@/assets/css/index.scss'; //这个分号一定要写，要不会报错
  @import '@/assets/css/user.scss'; //这个分号一定要写，要不会报错
  >>> .el-tabs__item.is-active,
  >>> .el-tabs__item:hover{
    color: #ff5733;
  }
  >>> .el-tabs__active-bar{
    background-color: #ff5733;
  }
  .userStatus1 {
    color: #19be6b;
  }
  .userStatus2 {
    color: #eb194d;
  }
  .userStatus3 {
    color: red;
  }
  .status_box{
    position: relative;
  }
  .add{
    width: 50px;
    margin: 7px 0 7px 10px;
    position: absolute;
    right: 0;
    >>> .el-button{
      padding: 0 10px;
      height: 35px;
      text-align: center;
      line-height: 35px;
      background-color: #ffffff;
      color: #333;
    }
  }
  .property{
    >>> .el-input{
      width: 198px;
      .el-input__inner{
        height: 35px;
        line-height: 35px;
      }
    }
  }
  >>> .el-form-item{
    margin-bottom: 8px;
  }
  >>> .el-form-item__label{
    color: #333333;
    line-height: 35px;
    >>> .el-input,
    >>> .el-textarea{
      width: 400px;
      .el-input__inner{
        height: 35px;
        line-height: 35px;
      }
    }
  }
  >>> .el-form-item__content{
    line-height: 35px;
  }
  >>> .el-input__inner{
    margin-left: 0!important;
  }
  >>> .el-dialog{
    .el-input{
      width: 400px;
    }
    .lng,.lat{
      width: 198px;
    }
  }
  >>> .el-dialog__footer{
    text-align: left;
    margin-left: 100px;
  }
  .line{
    color: #409EFF;
  }
  // 绑定会员卡部分
  .bindname{
    width: 100%;
    height: 50px;
    padding: 0 30px;
    box-sizing: border-box;
    line-height: 30px;
    font-size: 16px;
  }
  >>>.el-checkbox{
    width: 100%;
    height: 30px;
    line-height: 30px;
    font-size: 16px;
    padding: 0 100px;
    box-sizing: border-box;
    i{
      font-style: normal;
    }
  }
  >>>.el-checkbox__label{
    font-size: 16px;
  }
</style>
